package com.elm.dao;

import com.elm.entity.Business;
import com.elm.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BusinessDao {

    public Business getBusinessById(int businessId) {
        String sql = "select * from business where businessId=?";
        Business business = new Business();
        try(Connection connection = DBUtil.getConnection();
            PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setInt(1, businessId);
            ResultSet rs = ps.executeQuery();
            if(rs.next()) {
                packageBusiness(business, rs);
            }
            return business;
        }catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }



    public List<Business> getBusinessByOrderTypeId(String orderTypeId) throws SQLException {
        String sql = "select * from business where orderTypeId=?";
        List<Business> businesses = new ArrayList<>();
        try(Connection connection = DBUtil.getConnection();
            PreparedStatement ps = connection.prepareStatement(sql)) {
            ps.setString(1, orderTypeId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Business business = new Business();
                packageBusiness(business, rs);
                businesses.add(business);
            }
            return businesses;
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 包装店铺信息的方法
     * @param business
     * @param rs
     * @throws SQLException
     */
    private void packageBusiness(Business business, ResultSet rs) throws SQLException {
        business.setBusinessId(rs.getInt("businessId"));
        business.setBusinessName(rs.getString("businessName"));
        business.setBusinessAddress(rs.getString("businessAddress"));
        business.setBusinessImg(rs.getString("businessImg"));
        business.setBusinessExplain(rs.getString("businessExplain"));
        business.setStarPrice(rs.getDouble("starPrice"));
        business.setDeliveryPrice(rs.getDouble("deliveryPrice"));
        business.setOrderTypeId(rs.getInt("orderTypeId"));
        business.setRemarks(rs.getString("remarks"));
    }
}
